package com.zq.zqplayer.test

import android.app.job.JobParameters
import android.app.job.JobService
import android.os.Handler
import android.os.Message
import android.util.Log
import android.widget.Toast




class JobSchedulerService : JobService() {
    override fun onStartJob(params: JobParameters?): Boolean {
        // 返回true，表示该工作耗时，同时工作处理完成后需要调用jobFinished销毁
        Log.i("ziq", "onStartJob ")
        Thread.sleep(5000)
        mJobHandler.sendMessageDelayed(Message.obtain(mJobHandler, 1, params), 5000)
        Log.i("ziq", "onStartJob params: ${params?.jobId} ${params?.extras?.get("job-key")}")
        return true
    }

    override fun onStopJob(params: JobParameters?): Boolean {
        Log.i("ziq", "onStopJob params: ${params?.jobId}")
        return true
    }

    // 创建一个handler来处理对应的job
    private val mJobHandler: Handler = Handler(object : Handler.Callback {
        // 在Handler中，需要实现handleMessage(Message msg)方法来处理任务逻辑。
        override fun handleMessage(msg: Message): Boolean {
            Toast.makeText(applicationContext, "JobService task running", Toast.LENGTH_SHORT).show()
            // 调用jobFinished
            Log.i("ziq", "jobFinished params: ${(msg.obj as JobParameters).jobId}")
            jobFinished(msg.obj as JobParameters, true)
            return true
        }
    })
}